package wechat.confirmation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wechat.resources.AppFilter;
import wechat.resources.InstanceResource;
import wechat.util.Configure;
import wechat.util.crypto.CryptoUtil;

public class Confirmation {
	private static Logger log = LoggerFactory.getLogger(Confirmation.class);
	
	public static boolean confirm(String signature, String timestamp, String nonce) {
		
		log.info("Confirmation  signature=" + signature + " timestamp=" + timestamp + " nonce=" + nonce);

		List<String> checkList = new ArrayList<String>();
		checkList.add(Configure.getToken());
		checkList.add(timestamp);
		checkList.add(nonce);

		Collections.sort(checkList);

		String sha1Result = CryptoUtil.getSha1(checkList.get(0) + checkList.get(1) + checkList.get(2));

		log.info("Confirmation  sha1Result=" + sha1Result);

		if (signature.equals(sha1Result)) {
			return true;
		}
		
		return false;

	}
	
	public static boolean confirm(String appid,String signature, String timestamp, String nonce) {
		
		log.info("Confirmation  signature=" + signature + " timestamp=" + timestamp + " nonce=" + nonce);
		
		InstanceResource instanceResource = AppFilter.chooseApp(appid);
		
		List<String> checkList = new ArrayList<String>();
		checkList.add(instanceResource.getToken());
		checkList.add(timestamp);
		checkList.add(nonce);

		Collections.sort(checkList);

		String sha1Result = CryptoUtil.getSha1(checkList.get(0) + checkList.get(1) + checkList.get(2));

		log.info("Confirmation  sha1Result=" + sha1Result);

		if (signature.equals(sha1Result)) {
			return true;
		}
		
		return false;

	}
}
